using DG.Tweening;
using UnityEngine;

public class CartMove : MonoBehaviour
{
    private float speed = 200f; // 物体的移动速度
    private float screenWidth;
    private float objectWidth = 600f;
    private float leftLimit;
    private float rightLimit;
    private float moveDirection = 1f;

    void Start()
    {
        // 获取Canvas的宽度
        RectTransform canvasRect = GameObject.Find("Canvas").GetComponent<RectTransform>();
        screenWidth = canvasRect.rect.width;



        // 计算物体的最左边和最右边的边界
        leftLimit = -screenWidth / 2 + objectWidth / 2;
        rightLimit = screenWidth / 2 - objectWidth / 2;
    }


    void Update()
    {
        // 每帧更新物体的位置，根据当前的移动方向来移动
        transform.Translate(Vector3.right * speed * moveDirection * Time.deltaTime);

        // 判断是否到达最右边
        if ((transform as RectTransform).anchoredPosition.x > rightLimit)
        {
            // 到达最右边时反向移动
            moveDirection = -1f;
        }
        // 判断是否到达最左边
        else if ((transform as RectTransform).anchoredPosition.x < leftLimit)
        {
            // 到达最左边时反向移动
            moveDirection = 1f;
        }
    }
}